package cn.tedu.sp02.controller;

import cn.tedu.sp01.pojo.Item;
import cn.tedu.sp01.service.ItemService;
import cn.tedu.sp01.web.util.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Random;

@RestController
@Slf4j
public class ItemController {
    @Autowired
    private ItemService itemService;

    //注入端口号 --是为了后面测试集群服务器负载均衡
    @Value("${server.port}")
    private int port;

    //用来获取订单中的商品列表
    @GetMapping("/{orderId}")
    public JsonResult<List<Item>> getItem(@PathVariable String orderId) throws InterruptedException {
        List<Item> items=itemService.getItems(orderId);
        log.info("获取商品列表，orderId="+orderId);
        //随机延迟
        if (Math.random()<0.9) {
            int t = new Random().nextInt(5000);
            System.out.println("延迟： " + t);
            Thread.sleep(t);
        }
        return JsonResult.ok().msg("server.port="+port).data(items);
    }
    //减少商品库存
    //RequestBody - 完整地接收请求协议体数据
    @PostMapping("/decreaseNumber")
    public JsonResult<?> decreaseNumber(@PathVariable List<Item> items){
        itemService.decreaseNumber(items);
        return JsonResult.ok().msg("减少商品库存成功");
    }
}
